package com.stx.jeepay.payment.service;

import com.stx.jeepay.core.entity.TransferOrderEntity;
import com.stx.jeepay.core.service.TransferOrderService;
import com.stx.jeepay.core.utils.SpringBeansUtil;
import com.stx.jeepay.payment.channel.ITransferService;
import com.stx.jeepay.payment.model.MchAppConfigContext;
import com.stx.jeepay.payment.rqrs.msg.ChannelRetMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class TransferOrderReissueService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;
    @Autowired
    private TransferOrderService transferOrderService;
    @Autowired
    private PayMchNotifyService payMchNotifyService;

    /**
     * 处理转账订单
     **/
    public ChannelRetMsg processOrder(TransferOrderEntity transferOrder) {
        try {
            String transferId = transferOrder.getTransferId();

            // 查询转账接口是否存在
            ITransferService transferService =
                    SpringBeansUtil.getBean(transferOrder.getIfCode() + "TransferService", ITransferService.class);

            // 转账上游实现不存在
            if (transferService == null) {
                log.error("{} interface not exists!", transferOrder.getIfCode());
                return null;
            }

            // 查询商户配置
            MchAppConfigContext mchAppConfigContext =
                    configContextQueryService.queryMchInfoAndAppInfo(transferOrder.getMchNo(), transferOrder.getAppId());

            ChannelRetMsg channelRetMsg = transferService.query(transferOrder, mchAppConfigContext);
            if (channelRetMsg == null) {
                log.error("channelRetMsg is null");
                return null;
            }

            log.info("补单[{}]查询结果为：{}", transferId, channelRetMsg);

            // 查询成功
            if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                // 转账成功
                transferOrderService.updateIng2Success(transferId, channelRetMsg.getChannelOrderId());
                payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
            } else if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL) {
                // 转账失败
                transferOrderService.updateIng2Fail(transferId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId(), channelRetMsg.getChannelErrCode());
                payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
            }

            return channelRetMsg;
        } catch (Exception e) {
            log.error("error transferId = {}", transferOrder.getTransferId(), e);
            return null;
        }
    }
}
